package dao

import (
	"dogapm"
	"fmt"
)

type skuDao struct {
	ID    uint   `gorm:"primarykey"`
	Num   int32  `gorm:"num" json:"num"`
	Name  string `gorm:"name" json:"name"`
	Price int32  `gorm:"price" json:"price"`
}

func (s *skuDao) TableName() string {
	return "t_sku"
}

var SkuDao = &skuDao{}

func (s *skuDao) Get(id int64) (skuDao, bool) {
	rows := dogapm.Infra.MySqlDB.Find(&s, "id = ?", id).RowsAffected
	if rows == 0 {
		return skuDao{}, false
	}
	return *s, true
}

func (s *skuDao) Decr(id int64, num int32) (bool, error) {
	var db = dogapm.Infra.MySqlDB
	if err := db.First(s, "id=?", id).Error; err != nil {
		return false, err
	} else if s.Num >= num {
		db.Model(s).Where("id = ?", id).Update("num", s.Num-num)
	} else {
		return false, fmt.Errorf("cannot decrement, as the current number is less than the decrement amount")
	}
	return true, nil
}
